package com.google.code.avajhelpdesk.pages.panels;

import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;

import com.google.code.avajhelpdesk.MyWebSession;
import com.google.code.avajhelpdesk.entities.User;
import com.google.code.avajhelpdesk.pages.HomePage;
import com.google.code.avajhelpdesk.pages.UserWorkbenchPage;
import com.google.code.avajhelpdesk.pages.users.UserProfileView;


public class SignedUserInfoPanel extends Panel {

	@SuppressWarnings("unchecked")
	private static final class LogoutLink extends Link {
		private static final long serialVersionUID = 1L;

		private LogoutLink(String id) {
			super(id);
		}

		public void onClick() { 
		    getSession().invalidate(); 
		    getRequestCycle().setRedirect(true); 
		    setResponsePage(HomePage.class); 
		}
	}

	private static final long serialVersionUID = 1L;

	public SignedUserInfoPanel(String id) {
		super(id);
		
		Link workbenchLink = new Link("user-workbench-link") {
			@Override
			public void onClick() {
				User user = ((MyWebSession) getSession()).getUser();
				
				getRequestCycle().setRedirect(true);
				setResponsePage(new UserProfileView(user));
			}
		};
		
		Label label = new Label("user-name-info", getUserName());

		add(workbenchLink);
		workbenchLink.add(label);
		add(new LogoutLink("logout-link"));
	}

	private String getUserName() {
		MyWebSession session = (MyWebSession) AuthenticatedWebSession.get();
		if (!session.isSignedIn()) {
			throw new IllegalStateException("User not signed in");
		}
		return session.getUser().getUsername();
	}

}
